/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.

package pin.db.procedures;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.sql.Timestamp;
import java.util.Collection;
import java.util.Date;
import java.util.Vector;
import javax.naming.AuthenticationException;
import javax.sql.DataSource;
import org.apache.torque.TorqueException;
import pin.db.dbcp.DBUtils;

import pin.db.structure.Group;
import pin.db.structure.Role;
import pin.db.structure.User;
import pin.db.structure.UserPeer;
import pin.db.structure.UserRole;
import pin.db.torque.Torque;

/**
 *
 * @author HuXiaodi

public class UserUtils extends UserPeer {

    private UserUtils() {
    }

    public static boolean deleteUser(int id) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public static boolean isUsernameAvailable(String username, Connection conn) throws SQLException {
        return (UserPeer.getUserByUsername(username, conn) == null);
    }

    public static Collection<Group> getUserGroups(User user, Connection conn) throws SQLException {
        Collection<Role> rs = getUserRoles(user, conn);
        Collection<Group> gs = new Vector<Group>();
        for (Role r : rs) {
            gs.add(r.getGroupThroughGroupId(conn));
        }
        return gs;

    }

    public static Collection<Role> getUserRoles(User user, Connection conn) throws SQLException {
        Collection<UserRole> uc = user.getUserRoleCollection(conn);
        Collection<Role> rs = new Vector<Role>();
        for (UserRole u : uc) {
            rs.add(u.getRoleThroughRoleId(conn));
        }
        return rs;


    }

    public static User login(String username, String password, String token, Connection conn) throws SQLException {
        User user = UserPeer.getUserByUsername(username, conn);
        if (!user.getPassword().equals(password)) {
            //等录失败，记录
            return null;
        }
        Date now = new Date();
        if (token != null) {
            user.setCookieString(token);
            Date expires = new Date();
            expires.setTime(now.getTime() + 1000 * 60 * 60 * 24 * 7);
            user.setExpiresDate(new Timestamp(expires.getTime()));
        }
        UserPeer.update(user, conn);
        
        return user;
        /* Criteria c = new Criteria();
        c.add(UserPeer.USERNAME, username);
        //c.add(UserPeer.PASSWORD, password);
        c.setLimit(1);
        List l = UserPeer.doSelect(c);
        if (l.isEmpty()) {
        throw new UserNotExsitedException();
        }
        User user = (User) l.get(0);
        if (!user.getPassword().equals(password)) {
        throw new AuthenticationException();
        }
        if (user.getIslocked()) {
        throw new UserLockedException();
        }
        if (user.getIsdeleted()) {
        throw new UserDeletedException();
        }
        Date now = new Date();
        if (token != null) {
        user.setCookiestring(token);
        Date expires = new Date();
        expires.setTime(now.getTime() + 1000 * 60 * 60 * 24 * 7);
        user.setExpiresdate(expires);
        }
        if (!user.getIsonline()) {
        Date lastLoginDate = user.getLastlogindate();
        Date lastActiveDate = user.getLastactivedate();
        int lastSeconds = (int) (lastActiveDate.getTime() - lastLoginDate.getTime()) / 1000;
        user.setOnlinetime(lastSeconds + user.getOnlinetime());
        user.setLastlogindate(now);
        user.setLastactivedate(now);
        user.setLogintimes(user.getLogintimes() + 1);
        //user.
        user.setIsonline(true);
        } else {
        active(user);
        }
        if (user.isModified()) {
        UserPeer.doUpdate(user);
        }
        return user;
   



    }

    private static void active(User user) {
    /*
    Date now = new Date();
    Date lastActiveDate = user.getLastactivedate();
    int lastSeconds = (int) (now.getTime() - lastActiveDate.getTime()) / 1000;
    user.setOnlinetime(lastSeconds + user.getOnlinetime());

    }

    public static boolean logout(String username) {
        /*
        Criteria c = new Criteria();
        c.add(UserPeer.USERNAME, username);
        //c.add(UserPeer.PASSWORD, password);
        c.setLimit(1);
        List l = UserPeer.doSelect(c);
        if (l.isEmpty()) {
        throw new UserNotExsitedException();
        }
        User user = (User) l.get(0);
        user.setCookiestring(null);
        user.setExpiresdate(null);
        if (user.getIsonline()) {
        active(user);
        user.setIsonline(false);
        }
        UserPeer.doUpdate(user);
        return true;
        //throw new UnsupportedOperationException("Not supported yet.");
 
        return false;
    }

    public static boolean register(User user) {
        /*
        Criteria c = new Criteria();
        c.add(UserPeer.USERNAME, user.getUsername());
        c.or(UserPeer.NICENAME, user.getNicename());
        //c.add(UserPeer.NICENAME,user.getNicename(),SqlEnum.);
        List l = UserPeer.doSelect(c);
        if (!l.isEmpty()) {
        throw new UserExisitedException();
        }
        user.setOnlinetime(0);
        Date now = new Date();
        user.setRegisterdate(now);
        UserPeer.doInsert(user);
        return true;

        return false;
    }

    public static void register(String username, String password, String nicename) {
    /*
    Connection conn;
    try {
    conn = Transaction.begin(Torque.getDefaultDB());
    String sql;
    sql = "INSERT INTO `user` SET " +
    "user.REGISTERDATE=?, " +
    "user.USERNAME=?, " +
    "user.PASSWORD=?, " +
    "iser.NICENAME=? ;";
    PreparedStatement pstmt = conn.prepareStatement(sql);
    Date now = new Date();
    pstmt.setDate(1, new java.sql.Date(now.getTime()));
    pstmt.setString(2, username);
    pstmt.setString(3, password);
    pstmt.setString(4, nicename);
    int rowsAffected = pstmt.executeUpdate();
    ResultSet rs = pstmt.getGeneratedKeys();
    rs.next();
    int userId = rs.getInt(1);
    RoleUtils.addUserToRole(userId, RoleUtils.ROLE_PERSONAL_USER);
    } catch (SQLException ex) {
    Logger.getLogger(UserUtils.class.getName()).log(Level.SEVERE, null, ex);
    throw new TorqueException(ex);
    }

    }

    public static boolean unDelete(User user) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public static boolean unLock(User user) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public static User getUserByCookieString(String cookieString, String username) {
        /*
        Criteria c = new Criteria();
        c.add(UserPeer.COOKIESTRING, cookieString);
        c.add(UserPeer.USERNAME, username);
        c.add(UserPeer.EXPIRESDATE, new Date(), SqlEnum.GREATER_THAN);
        List us = UserPeer.doSelect(c);
        if (!us.isEmpty()) {
        return (User) us.get(0);
        } else {
        throw new UserNotExsitedException();
        }
     
        return null;
    }

    public static void main(String[] args) throws Exception {

        DataSource ds = DBUtils.createDataSource();

        Connection conn = ds.getConnection();



        list(System.out, UserUtils.getUserByUserId(new Long(1), conn));
        conn.close();
    }

    public static void modifyUserInfo(String nicename) {

    }

    public static void changePassword(String username, String oldPassword, String newPassword) throws AuthenticationException, TorqueException, SQLException {
        Connection conn = null;
        try {
            conn = Torque.getConnection();
            changePassword(username, oldPassword, newPassword, conn);
        } finally {
            Torque.closeConnection(conn);
        }
    }

    public static void changePassword(String username, String oldPassword, String newPassword, Connection conn) throws AuthenticationException, SQLException {
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            String sql = "SELECT COUNT(*) FROM `user` WHERE username=? AND password=?;";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            pstmt.setString(2, oldPassword);
            rs = pstmt.executeQuery();
            if (!rs.next() || rs.getInt(1) == 0) {
                throw new AuthenticationException();
            }

            sql = "UPDATE `user` SET password=? WHERE username=?;";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, newPassword);
            pstmt.setString(2, username);
            if (pstmt.executeUpdate() == 0) {
                throw new AuthenticationException();
            }
        } finally {
            if (rs != null) {
                rs.close();
            }
        }



    }
}
 */
